<?php
namespace app\payment\logic;

use tp5_lib\common\logic\Logic;
use tp5_lib\account\contract\Trade;
use app\payment\model\PaymentModel;
use tp5_lib\user\model\UserModel;
use think\Db;
use tp5_lib\account\model\AccountLogModel;
use app\payment\model\RoyaltyModel;

class PaymentLogic extends Logic implements Trade
{
    /**
     * 商户收款链接
     */
    public function collectUrl($uid,$url)
    {
        //推广链接，如果使用其他APP扫描二维码，则跳转到推广链接
        // $host=$this->request->domain();
        //业务参数，顾客端APP端扫描二维码，解析参数并调用相应接口
        $params=[
            "referral"=>$uid,
            "module"=>"payment",
            "action"=>"pay",
            "payee"=>$uid,
        ];
        $separator = strpos("?",$url) ===false ? "?" : "&";
        return $url . $separator . http_build_query($params);
    }
    /**
     * 顾客支付
     * 扫描收款码付钱
     */
    public function pay($uid,$payee,$amount)
    {

    }

    /**
     * 预创建订单
     * 带有金额的付钱链接
     */
    public function precreate()
    {

    }
    /**
     * 付款方扫描预创建订单付钱
     */
    public function payOrder()
    {

    }
    
    /**
     * 付款方的付钱链接
     */
    public function payUrl()
    {

    }
    /**
     * 收款方收钱
     * 先预创建订单，然后扫描付款方的付款码
     */
    public function collect()
    {

    }
    /**
     * 创建支付订单
     */
    public function create($payer,$payee,$amount)
    {
        $model=new PaymentModel();
        $id=$model->db()->insertGetId([
            "payer"=>$payer,
            "payee"=>$payee,
            "amount"=>$amount,
            "time"=>time(),
        ]);
        return $id;
    }
    public function paySuccess($id)
    {
        $time=time();
        $model=new PaymentModel();
        /** @var Query $db */
        $db=Db::connect();
        $db->startTrans();
        try {
            if(!$record=$model->db()->where(["id"=>$id])->find()){
                $this->error="订单不存在";
                return false;
            }
            if($record["status"] != "0"){
                return true;
            }

            if(!$list=$this->royalty($id,$record["payer"],$record["payee"],$record["amount"])){
                return false;
            }
            $user_model=new UserModel();
            $log_model=new AccountLogModel();
            $extend_model=new RoyaltyModel();
            foreach($list as $item){
                $data=[
                    "handler"=>"0",
                    "user_id"=>$item["user_id"],
                    "previous"=>$item["previous"],
                    "money"=>$item["amount"],
                    "type"=>$item["type"],
                    "asso_id"=>$item["asso_id"],
                    "message"=>$item["message"],
                    "time"=>$time,
                ];
                $id=$log_model->db()->insertGetId($data);
                $extend=[
                    "id"=>$id,
                    "type"=>$item["type"],
                    "from"=>$item["from"],
                ];
                $extend_model->db()->insert($extend);
                $user_model->where(["id"=>$item["user_id"]])->setInc("money",$item["amount"]);
            }

            $sql=$model->db()->where(["id"=>$id])->fetchSql()->setField("status",1);
            $db->execute($sql);
            $db->commit();
            return true;
        }
        catch (\Exception $ex) {
            $db->rollback();
            $this->error="数据库操作错误:".$ex->getMessage();
            return false;
        }
    }
    public function royalty($id,$payer,$payee,$amount)
    {
        $merchant_list=$this->merchant($id,$payee,$amount);
        if($merchant_list === false) return false;

        $customer_list=$this->customer($id,$payer,$amount);
        if($customer_list === false) return false;

        return array_merge($merchant_list,$customer_list);
    }
    
    /**
     * 商家模式的分成计算
     * @param int $id 订单编号
     * @param int $uid 用户编号
     * @param float $amount 金额
     */
    public function merchant($id,$uid,$amount)
    {
        $setting=0.001;
        $user_model=new UserModel();
        if(!$user=$user_model->where(["id"=>$uid])->find()){
            $this->error="商户不存在";
            return false;
        }
        if(empty($user["referral"])){
            return [];
        }
        $royalty = $amount * $setting;
        return [
            ["user_id"=>$user["referral"],"previous"=>$user["money"],"amount"=>$royalty,"message"=>"商家收款分成","type"=>"royalty","asso_id"=>$id,"type"=>"merchant","from"=>$uid],
        ];
    }
    
    /**
     * 顾客模式的分成计算
     * @param int $id 订单编号
     * @param int $uid 用户编号
     * @param float $amount 金额
     */
    public function customer($id,$uid,$amount)
    {
        $setting=[
            "total"=>0.1,
            "ratio"=>[0.3,0.2,0.1,0.05],
        ];
        $user_model=new UserModel();
        if(!$user=$user_model->where(["id"=>$uid])->find()){
            $this->error="顾客不存在";
            return false;
        }
        $total = $amount * $setting["total"];
        $ratio = $setting["ratio"];
        $result=[
            ["user_id"=>$user["id"],"previous"=>$user["money"],"amount"=>$total * array_shift($ratio),"message"=>"顾客付款分成","type"=>"royalty","asso_id"=>$id,"type"=>"customer","from"=>$uid],
        ];
        foreach($ratio as $value){
            if(empty($user["referral"])){
                return $result;
            }
            $from=$user["id"];
            if(!$user=$user_model->where(["id"=>$user["referral"]])->find()){
                $this->error="推荐者不存在";
                return false;
            }
            $result[]=["user_id"=>$user["id"],"previous"=>$user["money"],"amount"=>$total * array_shift($ratio),"message"=>"顾客付款分成","type"=>"royalty","asso_id"=>$id,"type"=>"customer","from"=>$from];
        }
        
        return $result;
    }
    public function payClose($id)
    {
        return true;
    }
    public function payStatus($id)
    {
        return true;
    }
}
